/**@author: Administrator
 * @date: 2013-3-8
 * @Description:
 */
package org.benxiong.iplay.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import org.benxiong.iplay.R;
import org.benxiong.iplay.http.request.RequestFactory;
import org.benxiong.iplay.model.UserThumbnail;
import org.benxiong.iplay.type.MyListType;
import org.benxiong.iplay.type.SearchMemberType;
import org.benxiong.iplay.type.TimeType;
import org.benxiong.iplay.ui.adapter.MemListAdapter;
import org.benxiong.iplay.util.GlobalVar;
import org.benxiong.iplay.util.ImageUtil;
import org.benxiong.iplay.util.LogX;
import org.benxiong.iplay.util.ObjectConverter;
import org.benxiong.iplay.util.PathUtil;
import org.benxiong.iplay.util.PreferencesUtil;
import org.benxiong.iplay.util.ToastUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * @author Administrator
 * 
 */
public class MemberActivity extends BaseActivity implements OnItemClickListener {
	private GridView		mGridList;
	private MemListAdapter	mAdapter;
	private boolean			shoudlClearCache;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.benxiong.iplay.ui.BaseActivity#initView()
	 */
	@Override
	protected void initView() {
		GlobalVar.appContext = this;
		if (!PreferencesUtil.isLogin()) {
			finish();
			jumpToActivity(LoginActivity.class);
		} else {
			setContentView(R.layout.activity_member);
			GlobalVar.userName = PreferencesUtil.getLoginInfo().getString(PreferencesUtil.USERNAME, null);
			GlobalVar.password = PreferencesUtil.getLoginInfo().getString(PreferencesUtil.PASSWORD, null);

			mGridList = (GridView) findViewById(R.id.mem_list);

			mAdapter = new MemListAdapter(this);
			mGridList.setAdapter(mAdapter);
			mGridList.setOnItemClickListener(this);
			getLocation();
			if (GlobalVar.liveMemberList == null || GlobalVar.liveMemberList.size() == 0)
				reqData(SearchMemberType.Nearby, null, false);
			else {
				mAdapter.setData(GlobalVar.liveMemberList);

			}
		}
	}

	public void onResume() {
		super.onResume();

		// user has login, check user avator
		final File f = ImageUtil.getAvatorCache();
		if (f.exists()) {
			// check server profile user avator
			RequestParams rParam = new RequestParams();
			rParam.put("username", GlobalVar.userName);
			RequestFactory.getInstance().post(RequestFactory.URL_HAS_AVATOR,
					rParam, new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(String arg0) {
							// TODO Auto-generated method stub
							super.onSuccess(arg0);
							LogX.print("========onSUccess==" + arg0);
							try {

								if (shouldProcess(arg0)) {
									JSONObject json = new JSONObject(arg0);
									boolean exists = json.getBoolean("data");
									if (exists) {
										LogX.print("===exists===");
										// delete local file
										f.delete();
									} else {
										uploadAvator(f);
									}
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						@Override
						public void onFailure(Throwable arg0) {
							// TODO Auto-generated method stub
							super.onFailure(arg0);
							LogX.print("========onFailure==" + arg0.getMessage());
						}
					});
		}
	}

	private void uploadAvator(File f) {
		// after upload success, delete avator file
		RequestParams rParam = new RequestParams();
		rParam.put("type", "" + PhotoManagerActivity.PHOTO_TYPE_AVATOR);
		try {
			rParam.put("file", f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		RequestFactory.getInstance().post(RequestFactory.URL_UPLOAD_PHOTO,
				rParam, new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable arg0) {
						// TODO Auto-generated method stub
						super.onFailure(arg0);
						LogX.print("====Pic=onFailure====" + arg0.getMessage());
					}

					@Override
					public void onSuccess(String arg0) {
						// TODO Auto-generated method stub
						super.onSuccess(arg0);
						LogX.print("===Pic==onSuccess====" + arg0);
					}

				});

		LogX.print("=====get User path URL ====" + PathUtil.profilePictureUrl(GlobalVar.userName, null));
		LogX.print("=====delete local file====");
		// f.delete();
	}

	private void getLocation()
	{
		// 获取位置管理服务
		LocationManager locationManager;
		String serviceName = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) this.getSystemService(serviceName);
		// 查找到服务信息
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗

		String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
		Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
		updateToNewLocation(location);

		// 设置监听器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
		locationManager.requestLocationUpdates(provider, 2 * 1000, 10,
				new LocationListener() {

					@Override
					public void onStatusChanged(String provider, int status, Bundle extras) {

					}

					@Override
					public void onProviderEnabled(String provider) {

					}

					@Override
					public void onProviderDisabled(String provider) {

					}

					@Override
					public void onLocationChanged(Location location) {
						updateToNewLocation(location);
					}
				});
	}

	private void updateToNewLocation(Location location) {
		if (location != null) {
			GlobalVar.currentLocation = location;
		} else {
			ToastUtil.toast(R.string.gps_off_alert);
		}
	}

	private String getFilterByType(SearchMemberType smt) {
		if (smt == SearchMemberType.Popular) {
			return "timeType";
		} else if (smt == SearchMemberType.MyList) {
			return "myListType";
		}

		return null;
	}

	private void reqData(SearchMemberType smt, String filterValue, boolean forceUpdate) {
		final RequestParams rParam = new RequestParams();
		rParam.put("searchType", smt.name());
		String filterName = getFilterByType(smt);
		if (filterName != null) {
			rParam.put(filterName, filterValue);
		} else {
			// set longitude and latitude
			if (GlobalVar.currentLocation != null) {
				rParam.put("longitude", "" + GlobalVar.currentLocation.getLongitude());
				rParam.put("latitude", "" + GlobalVar.currentLocation.getLatitude());
			}
		}

		final BaseActivity ba = this;
		List<UserThumbnail> cached = GlobalVar.dataArchive.getUserThumbnailsMap().get(RequestFactory.URL_MEMBERS + rParam.toString());
		if (!forceUpdate && cached != null) {
			mAdapter.setData(cached);
			mGridList.setAdapter(mAdapter);
			return;
		}

		showLoading();
		RequestFactory.getInstance().post(RequestFactory.URL_MEMBERS, rParam, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable throwable) {
				super.onFailure(throwable);
				onReqFail();
			}

			@Override
			public void onSuccess(String s) {
				if (!ba.active)
					return;
				super.onSuccess(s);
				JSONObject ret;
				try {
					if (shouldProcess(s)) {
						ret = new JSONObject(s);
						JSONArray data = ret.getJSONArray("data");
						List<UserThumbnail> dataList = new ArrayList<UserThumbnail>();
						UserThumbnail snail;
						JSONObject obj;
						for (int i = 0; i < data.length(); i++) {
							obj = data.getJSONObject(i);
							snail = ObjectConverter.jsonToUserThumbnail(obj);
							dataList.add(snail);
						}
						GlobalVar.dataArchive.getUserThumbnailsMap().put(RequestFactory.URL_MEMBERS + rParam.toString(), dataList);
						LogX.print("cached key: " + RequestFactory.URL_MEMBERS + rParam.toString());
						mAdapter.setData(dataList);
						mGridList.setAdapter(mAdapter);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

	public String getCacheKey(String url, RequestParams param) {
		return url + param.toString();
	}

	@Override
	public void onMessage(Message msg) {

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.member_menu, menu);
		return true;
	}

	@Override
	public void handleClick(int buttonId) {

	}

	private void showTimeList() {
		TimeType[] values = TimeType.values();
		final String[] timeTypes = new String[values.length];

		for (int i = 0; i < values.length; i++) {
			timeTypes[i] = values[i].name();
		}

		new AlertDialog.Builder(this)
				.setTitle("Popular in ")
				.setItems(timeTypes, new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						reqData(SearchMemberType.Popular, timeTypes[which], true);
					}

				}).create().show();
	}

	private void showMyList() {
		MyListType[] values = MyListType.values();
		final String[] myTypes = new String[values.length];

		for (int i = 0; i < values.length; i++) {
			myTypes[i] = values[i].name();
		}

		new AlertDialog.Builder(this)
				.setTitle("Show members of")
				.setItems(myTypes, new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						reqData(SearchMemberType.MyList, myTypes[which], true);
					}

				}).create().show();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.nearby:
			reqData(SearchMemberType.Nearby, null, true);
			break;
		case R.id.popular:
			showTimeList();
			break;
		case R.id.my:
			showMyList();
			break;
		case R.id.search:
			final EditText input = new EditText(this);
			new AlertDialog.Builder(this).setTitle(R.string.input_alert)
					.setView(input).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// search by member name
							if (TextUtils.isEmpty(input.getText().toString())) {
								ToastUtil.toast(R.string.input_alert);
							} else {
								Intent intent = new Intent(MemberActivity.this, ProfileInfoActivity.class);
								intent.putExtra("username", input.getText().toString());
								startActivity(intent);
							}
						}
					}).setNegativeButton(android.R.string.cancel, null)
					.create().show();
			break;
		default:
			super.onOptionsItemSelected(item);
		}

		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		Intent intent = new Intent(this, ProfileInfoActivity.class);
		intent.putExtra("username", mAdapter.getItem(position).getUsername());
		startActivity(intent);
	}

}
